package tazadum.engine.event;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class SyncEventQueue {
	private final Map<String, PriorityQueue<Float>> points = new HashMap<String, PriorityQueue<Float>>();

	public void add(final String channel, final float time) {
		getOrCreate(channel).add(time);
	}

	public SyncEventChannel get(final String channel) {
		final PriorityQueue<Float> queue = getOrCreate(channel);
		return new SyncEventChannel() {
			@Override
			public void add(final float time) {
				queue.add(time);
			}

			@Override
			public void add(final float... times) {
				for (final float time : times) {
					queue.add(time);
				}
			}

			@Override
			public float get(final float time) {
				while (!queue.isEmpty() && queue.peek() < time) {
					queue.poll();
				}
				if (queue.isEmpty()) {
					return 0;
				}
				return queue.peek();
			}
		};
	}

	private PriorityQueue<Float> getOrCreate(final String channel) {
		if (!points.containsKey(channel)) {
			points.put(channel, new PriorityQueue<Float>());
		}
		return points.get(channel);
	}
}
